package models

import (
	"errors"
	"fmt"
	"regexp"
	"strings"
	"time"
	"xorm.io/builder"
)

type User struct {
	Id          int    `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	Type        string `xorm:"default '4' comment('用户类别，1：运管，2：驾校，3：教练，4：学员，5:考核员 6:安全员') ENUM('1','2','3','4','5','6')" form:"type"`
	Password    string `xorm:"not null comment('用户密码使用MD5加密存储') CHAR(32)" form:"password"`
	Name        string `form:"name" xorm:"not null comment('姓名') index VARCHAR(16)"`
	Sex         string `form:"sex" xorm:"default '1' comment('用户性别，1：男性， 2：女性') ENUM('1','2')"`
	Nation      string `form:"nation" xorm:"default '' comment('民族') VARCHAR(16)"`
	Phone       string `form:"phone"  xorm:"comment('手机号码，联系方式') unique VARCHAR(16)"`
	Mail        string `xorm:"default '' comment('用户电子邮箱地址') VARCHAR(64)" form:"mail"`
	Address     string `form:"address" xorm:"default '' comment('用户办公/家庭地址') VARCHAR(512)"`
	Nationality string `form:"nationality" xorm:"not null default '中国' comment('国籍') VARCHAR(32)"`
	District    string `xorm:"comment('区县行政区划代码') VARCHAR(6)" form:"district"`
	IdType      string `xorm:"default '1' comment('证件类型 1:身份证， 2:护照， 3:军官证， 4:其他') ENUM('1','2','3','4')" form:"id_type"`
	IdNumber    string `xorm:"not null comment('证件号') VARCHAR(32)" form:"id_number"`
	Native      string `xorm:"not null comment('籍贯') VARCHAR(6)" form:"native"`
	Sid         int    `xorm:"default 0 comment('学校id') INT(10)" form:"sid"`
	Cardid      string `xorm:"not null default '' comment('身份证ID号') VARCHAR(16)" form:"card_id"`
	Isused      string `xorm:"default '1' comment('1 正在使用   0已删除') ENUM('0','1')"`
	Remark      string `xorm:"comment('已删除的学员手机号') VARCHAR(16)"`
	ReidNumber  string `xorm:"VARCHAR(32)"`
	GroupId     int    `xorm:"-" form:"group_id"`
}

func (c *User) GetById(id string) (list User, err error) {
	if _, err = engine.Table("dts_user").Where("id = ?", id).Get(&list); err != nil {
		return list, err
	}
	return list, nil
}

// UserRole 用户角色关联表
type UserRole struct {
	Id        int       `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	UserId    int       `xorm:"not null comment('用户id外键关联dts_user中的id') index INT(11)"`
	RoleId    int       `xorm:"not null comment('角色id外键关联dts_role中的id') index INT(11)"`
	CreaterId int       `xorm:"comment('最近一次更新者id外键关联dts_user中的id') index INT(11)"`
	AddTime   time.Time `xorm:"not null comment('用户角色添加时间') DATETIME created"`
}

type Id struct {
	User_id int
}

func (c *UserRole) GetSchoolUser(id int) (list []*Id) {
	engine.Table("dts_user_role").Alias("ue").
		Where("ue.creater_id = ?", id).
		Find(&list)
	return
}

func HasPhone(phone string) bool {
	phone = strings.Replace(strings.Replace(phone, "t", "", -1), "t", "", -1)
	has, err := engine.Table("dts_user").Where("phone = ? && isused=? ", phone, "1").Exist()
	if has && err == nil {
		return true
	} else {
		return false
	}
}

func HasIdNumber(idNumber string) bool {
	idNumber = strings.Replace(strings.Replace(idNumber, "t", "", -1), "t", "", -1)
	has, err := engine.Table("dts_user").Where("id_number = ? and isused=?", idNumber, "1").Exist()
	if has && err == nil {
		return true
	} else {
		return false
	}
}

func (c *User) Edit(fields ...string) bool {
	var (
		err error
	)
	_, err = engine.Table("dts_user").Id(c.Id).Cols(fields...).Update(c)
	if err != nil {
		return false
	}
	return true
}

func (c *User) Delete() bool {
	var err error
	c.Isused = "0"
	c.Remark = c.Phone
	c.ReidNumber = c.IdNumber
	c.Phone = fmt.Sprint(time.Now().UnixNano() / 1e6)
	c.IdNumber = ""
	_, err = engine.Table("dts_user").Id(c.Id).Cols("isused", "remark", "phone", "id_number", "reid_number").Update(c)
	if err != nil {
		fmt.Println(err.Error())
		return false
	}
	return true
}

func (c *User) GetUserExists(filter builder.Cond) (has bool, list User, err error) {
	has, err = engine.Table("dts_user").
		And(filter).Get(&list)
	return has, list, err
}

func (c *User) CheckData(types int) (err error) {
	if c.Phone != "" && c.HasPhone(types) {
		return errors.New("手机号已存在")
	}
	if c.IdNumber != "" && c.HasIdNumber(types) {
		return errors.New("身份证号已存在")
	}
	if _, err = regexp.MatchString(`^(\d{17})([0-9]|X)$`, c.IdNumber); err != nil {
		return errors.New("身份证号码错误")
	}
	return nil
}

// types 1 添加   2 编辑
func (c *User) HasPhone(types int) bool {
	if types == 1 {
		has, err := engine.Table("dts_user").Where("phone = ? && isused=?", c.Phone, "1").Exist()
		if has && err == nil {
			return true
		} else {
			return false
		}
	} else {
		user := new(User)
		if _, err := engine.Table("dts_user").Where("phone = ? && isused=?", c.Phone, "1").Get(user); err != nil {
			return false
		} else {
			//phone 已经重复
			if c.Id == user.Id {
				//phone 没有变化
				return false
			} else {
				//已经存在该phone了
				return true
			}
		}
	}
	return true
}

// types 1 添加   2 编辑
func (c *User) HasIdNumber(types int) bool {
	//id_number := strings.Replace(strings.Replace(c.IdNumber, "t", "", -1), "t", "", -1)
	if types == 1 {
		has, err := engine.Table("dts_user").Where("id_number = ? and isused=? and type = ?", c.IdNumber, "1", c.Type).Exist()
		if has && err == nil {
			return true
		} else {
			return false
		}
	} else {
		user := new(User)
		if _, err := engine.Table("dts_user").Where("id_number = ? and isused=? and type = ?", c.IdNumber, "1", c.Type).Get(user); err != nil {
			return false
		} else {
			//如果编辑的id_number 已经重复
			if c.Id == user.Id {
				//id_number 没有变化
				return false
			} else {
				//已经存在该id_number了
				return true
			}
		}
	}
	return true
}
